package com.wwzh.interview.study.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone implements Runnable{
    public synchronized void sendSms() throws Exception{
        System.out.println(Thread.currentThread().getName()+"线程 invoked sendSms()");
        sendSmail();
    }
    public synchronized void sendSmail() throws Exception{
        System.out.println(Thread.currentThread().getName()+"线程 invoked sendSmail()");
    }

    Lock lock = new ReentrantLock();
    @Override
    public void run() {
       set();
    }

    public void set(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 获取了锁");
            get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+" 释放了了锁");
            lock.unlock();
        }
    }

    public void get(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+" 获取了锁");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(Thread.currentThread().getName()+" 释放了了锁");
            lock.unlock();
        }
    }
}

public class ReenterLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(()->{
            try {
                phone.sendSms();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t1").start();

        new Thread(()->{
            try {
                phone.sendSms();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t2").start();
//        new Thread(()->{
//            try {
//                phone.set();
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        },"t3").start();
//
//        new Thread(()->{
//            try {
//                phone.set();
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        },"t4").start();


        Thread t3 = new Thread(phone);
        Thread t4 = new Thread(phone);
        System.out.println();
        System.out.println();
        System.out.println();
        System.out.println();
        t3.start();
        t4.start();
    }
}
